import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/b2blabel/b2blabelmodel.dart';
import 'package:opene/ui/b2cpick/b2cpickcategoryscreen.dart';
import 'package:opene/ui/b2cpick/b2cpickmodel.dart';
import 'package:opene/ui/tally/tallymodel.dart';
import 'package:opene/ui/tally/tallyskuscreen.dart';
import 'package:toast/toast.dart';

class B2BLabelLPNScreen extends StatelessWidget {
  String order;
  B2BLabelLpn b2bLabelLpn;

  B2BLabelLPNScreen({this.order,this.b2bLabelLpn});

  @override
  Widget build(BuildContext context) {
    return B2BLabelLPNScreenPage(order: order,b2bLabelLpn: b2bLabelLpn);
  }
}

class B2BLabelLPNScreenPage extends StatefulWidget {
  String order;
  B2BLabelLpn b2bLabelLpn;

  B2BLabelLPNScreenPage({this.order,this.b2bLabelLpn});

  @override
  _B2BLabelLPNScreenPageState createState() => _B2BLabelLPNScreenPageState(order: order,b2bLabelLpn: b2bLabelLpn);
}

class _B2BLabelLPNScreenPageState extends BaseState<B2BLabelLPNScreenPage> {
  String order;
  B2BLabelLpn b2bLabelLpn;

  final TextEditingController lengthEditingController = TextEditingController();
  final TextEditingController widthEditingController = TextEditingController();
  final TextEditingController heightEditingController = TextEditingController();
  FocusNode lengthFocusNode = FocusNode();
  FocusNode widthFocusNode = FocusNode();
  FocusNode heightFocusNode = FocusNode();

  _B2BLabelLPNScreenPageState({this.order,this.b2bLabelLpn});

  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();

  int index = 0, position;
  List<ChildPick> data = new List();

  String tvSku,tvLwh,tvLogisticsType,tvNote;
  bool layoutLogisticsType=false;

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "B2BLabel:LPN";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setData();
  }
  @override
  void dispose() {
    lengthFocusNode.dispose(); // 不要忘记销毁FocusNode
    widthFocusNode.dispose(); // 不要忘记销毁FocusNode
    heightFocusNode.dispose(); // 不要忘记销毁FocusNode
    super.dispose();
  }
  @override
  Widget getViewBinding() {
    return Container(
      margin: EdgeInsets.only(left: 15, right: 15, top: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only( top: 0,),
            child: Row(
              children: [
                Text(
                  "B2B JOB: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(Utils.getStringisEmpty(order),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only( top: 2,),
            child: Row(
              children: [
                Text(
                  "Logistics type: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(Utils.getStringisEmpty(b2bLabelLpn.logisticsType),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
              ],
            ),
          ),

          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 10),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  CheckLpn(text);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        CheckLpn(text);
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan or input outbound lpn",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Text(
            "Pallet Size",
            style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
          ),
          SizedBox(height: 5,),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: setPhotoView("length:  ",  "inch", lengthEditingController,lengthFocusNode),
              ),
              Expanded(
                flex: 1,
                child: setPhotoView("width:  ",  "inch", widthEditingController,widthFocusNode),
              ),
            ],
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: setPhotoView("height:  ",  "inch", heightEditingController,heightFocusNode),
              ),
              Expanded(
                flex: 1,
                child: Text(""),
              ),
            ],
          ),

          Text(Utils.getStringisEmpty(tvSku),
            style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
          ),
          Text(Utils.getStringisEmpty(tvLwh),
            style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
          ),
          Visibility(
            visible: layoutLogisticsType,
              child:   Container(
                margin: EdgeInsets.only( top: 2,),
                child: Row(
                  children: [
                    Text(
                      "Estimated pallets: ",
                      style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                    ),
                    Expanded(
                      child: Text(Utils.getStringisEmpty(tvLogisticsType),
                        style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                      ),
                    ),
                  ],
                ),
              ),),
          Container(
            margin: EdgeInsets.only( top: 2,),
            child: Row(
              children: [
                Text(
                  "Note: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(Utils.getStringisEmpty(tvNote),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Container setPhotoView(String hintText, String hint, TextEditingController editingController,FocusNode focusNode) {
    return Container(
      margin: const EdgeInsets.only(left: 0, top: 10, right: 0, bottom: 0),
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(
            flex: 1, //设置权重
            child: Container(
              margin: EdgeInsets.only(top: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Text(
                    hintText,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
              flex: 2, //设置权重
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 70,
                    child: ConstrainedBox(
                      constraints: BoxConstraints(maxHeight: 30),
                      child: TextField(
                        focusNode: focusNode,
                        keyboardType: TextInputType.number,
                        controller: editingController,
                        textInputAction: TextInputAction.next,
                        // autofocus: true,
                        decoration: InputDecoration(
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: MyAppTheme.nearlyBlue,
                            ),
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点之外的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点时的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          hintText: hint,
                          filled: true,
                          fillColor: MyAppTheme.white,
                          //隐藏下划线
                          //border: InputBorder.none,
                          hintStyle: const TextStyle(color: Colors.grey),
                          contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                        ),
                        onChanged: (text) {
                          if (!Utils.isDouble(text)) {
                            editingController.text = "";
                            return;
                          }
                        },
                      ),
                    ),
                  ),
                ],
              )),
        ],
      ),
    );
  }
  void setData() {
    setState(() {
      tvSku="Customer Requirement: ";
      tvLwh="pallet size require: ${Utils.getStringisDouble(b2bLabelLpn.length)}*${Utils.getStringisDouble(b2bLabelLpn.width)}*${Utils.getStringisDouble(b2bLabelLpn.height)}" ;

      if (Utils.isEmpty(b2bLabelLpn.note)) {
        tvNote="";
      } else {
        tvNote=Utils.getStringisEmpty(b2bLabelLpn.note);
      }

      if ((b2bLabelLpn.isLpn != null)&&(b2bLabelLpn.isLpn == 1)) {
        layoutLogisticsType=true;
        tvLogisticsType=Utils.getStringisInteger(b2bLabelLpn.lpnQty);
      } else {
        layoutLogisticsType=false;
      }
    });
  }
  @override
  void setNext() {
    ToastContext().init(context);
    if (Utils.isEmpty(textEditingController.text)) {
      Toast.show("scan or input outbound lpn", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    B2BLabelLpnQr b2BLabelLpnQr = new B2BLabelLpnQr();
    b2BLabelLpnQr.jobId =order;
    b2BLabelLpnQr.lpn =textEditingController.text;

    if ((b2BLabelLpn.backend!=null)&&(b2BLabelLpn.backend!=1)&&(b2BLabelLpn.backend!=2)){
      String length = lengthEditingController.text;
      if (!judgeType(length, "Please enter the length")) {
        return;
      }
      String width = widthEditingController.text;
      if (!judgeType(width, "Please enter the width")) {
        return;
      }
      String height  = heightEditingController.text;
      if (!judgeType(height, "Please enter the height")) {
        return;
      }
      double l = double.parse(length);
      double w = double.parse(width);
      double h = double.parse(height);

      if ((l<40)||(w<40)){
        this.hint = "size can not exceed customer requirement";
        Toast.show("size can not exceed customer requirement", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }
      if ( (w<48)&&(l<48)){
        this.hint ="size can not exceed customer requirement";
        Toast.show("size can not exceed customer requirement", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }

      b2BLabelLpnQr.length = l;
      b2BLabelLpnQr.width =w;
      b2BLabelLpnQr.height =h;

    }

  }
  bool judgeType(String mold, String hint) {
    if (Utils.isEmpty(mold)) {
      this.hint = hint;
      Toast.show(hint, duration: Toast.lengthShort, gravity: Toast.bottom);
      return false;
    }
    if (mold==null) {
      this.hint = hint;
      Toast.show(hint, duration: Toast.lengthShort, gravity: Toast.bottom);
      return false;
    }
    if (!Utils.isDouble(mold)) {
      this.hint = hint;
      Toast.show(hint, duration: Toast.lengthShort, gravity: Toast.bottom);
      return false;
    }
    if (double.parse(mold)<=0) {
      this.hint = hint;
      Toast.show(hint, duration: Toast.lengthShort, gravity: Toast.bottom);
      return false;
    }
    return true;
  }
  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
  }

  void checkB2b(String order) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.checkB2b+"/"+order);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {

      b2bLabelLpn = B2BLabelLpn.fromJson(baseResponse.data);
      setData();
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  B2BLabelLpn b2BLabelLpn;
  void CheckLpn(String lpn) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context,title: "Check...");
    } catch (e) {
      e.toString();
    }
    Map<String, dynamic> map = new HashMap();
    map["lpn"] = lpn;
    map["type"] = "B2B";
    map["jobId"] = order;

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.app_lpn, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        B2BLabelLpn b2BLabelLpn = B2BLabelLpn.fromJson(baseResponse.data);
        lengthEditingController.text = Utils.getStringisDouble(b2BLabelLpn.length);
        widthEditingController.text = Utils.getStringisDouble(b2BLabelLpn.width);
        heightEditingController.text = Utils.getStringisDouble(b2BLabelLpn.height);

      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void palletSize(B2BLabelLpnQr b2BLabelLpnQr) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    var json = jsonEncode(b2BLabelLpnQr);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.pick_b2c_v2_queryPendingPicks, method: BaseMethod.post, data: json);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        List<B2BProcessDetails> b2BProcessDetails = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => B2BProcessDetails.fromJson(userJson)).toList());

        B2BProcess b2BProcess = new B2BProcess();
        b2BProcess.process = 2;
        b2BProcess.jobId = order;
        b2BProcess.lpn = b2BLabelLpnQr.lpn;
        b2BProcess.skuQtyList = b2BProcessDetails;
        // Navigator.push(
        //   context,
        //   MaterialPageRoute(builder: (context) => B2CPickCategoryScreen(b2cPickBean: b2cPickBean,pickupPol3OBLPN:pickupPol3OBLPN)),
        // ).then((value) => {getTallyContainerNo()});
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }
}
